<template>
  <div class="home-container">
    <el-row :gutter="20">
      <el-col :span="24">
        <el-card class="welcome-card">
          <h2>欢迎使用健康管理系统</h2>
          <p>今天是 {{ currentDate }}，祝您身体健康！</p>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" class="mt-20">
      <el-col :span="12">
        <el-card class="stat-card">
          <template #header>
            <div class="card-header">
              <h3>健康日志统计</h3>
            </div>
          </template>
          <div class="chart-container" ref="healthLogChartRef"></div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card class="stat-card">
          <template #header>
            <div class="card-header">
              <h3>最新公告</h3>
            </div>
          </template>
          <div v-if="announcements.length > 0">
            <el-timeline>
              <el-timeline-item
                v-for="item in announcements"
                :key="item.id"
                :timestamp="item.createTime"
                placement="top"
              >
                <el-card>
                  <h4>{{ item.title }}</h4>
                  <p>{{ item.content }}</p>
                  <el-button type="primary" v-show="item.fileName" @click="downloadFile(item.fileName)">附件</el-button>
                </el-card>
              </el-timeline-item>
            </el-timeline>
          </div>
          <div v-else class="empty-data">
            暂无公告
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import {onMounted, ref} from 'vue'
import {get} from '@/utils/request'
import * as echarts from 'echarts'
import dayjs from 'dayjs'
import type {Announcement} from '@/types/announcement'

const currentDate = dayjs().format('YYYY年MM月DD日')
const healthLogChartRef = ref<HTMLElement>()
const announcements = ref<Announcement[]>([])

// 初始化图表
const initHealthLogChart = (data: any) => {
  if (!healthLogChartRef.value) return

  const chart = echarts.init(healthLogChartRef.value)

  const option = {
    title: {
      text: '近7天健康数据'
    },
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: ['血糖', '血压(收缩压)', '血压(舒张压)']
    },
    xAxis: {
      type: 'category',
      data: data.createTime
    },
    yAxis: [
      {
        type: 'value',
        name: '血糖',
        min: 40,
        max: 200
      },
      {
        type: 'value',
        name: '血压(mmHg)',
        min: 50,
        max: 200
      }
    ],
    series: [
      {
        name: '血糖',
        type: 'line',
        data:  data.bloodSugar
      },
      {
        name: '血压(收缩压)',
        type: 'line',
        yAxisIndex: 1,
        data: data.bloodPressureSystolic
      },
      {
        name: '血压(舒张压)',
        type: 'line',
        yAxisIndex: 1,
        data: data.bloodPressureDiastolic
      }
    ]
  }

  chart.setOption(option)

  // 响应窗口大小变化
  window.addEventListener('resize', () => {
    chart.resize()
  })
}
const downloadFile = (path: string)=>{
  /*console.log(path)
  //downloadFiles(path);
  window.location.href='http://localhost:80181/files/download?path=' + path;*/

  try {
    // 1. 验证路径
    const safePath = path.replace(/\.\.\//g, '');

    // 2. 编码参数
    const encodedPath = encodeURIComponent(safePath);

    // 3. 触发下载
    window.location.href = `http://localhost:8881/files/download?path=${encodedPath}`;

  } catch (error) {
    console.error('下载错误:', error);
    alert('文件路径无效，请检查后重试。');
  }
}

// 获取健康日志数据
const fetchHealthLogData = async () => {
  try {
    const res = await get('/health-log/stats')
     console.log(res)
    initHealthLogChart(res)
  } catch (error) {
    console.error('获取体检日志数据失败:', error)
  }
}

// 获取公告列表
const fetchAnnouncements = async () => {
  try {
    const res = await get('/announcements/latest')
    console.log(res);
    announcements.value = res
  } catch (error) {
    console.error('获取公告列表失败:', error)
  }
}

onMounted(() => {
  fetchHealthLogData()
  fetchAnnouncements()
})
</script>

<style scoped>
.home-container {
  padding: 20px;
}

.mt-20 {
  margin-top: 20px;
}

.welcome-card {
  background-color: #ecf5ff;
}

.stat-card {
  height: 400px;
}

.chart-container {
  width: 100%;
  height: 300px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.empty-data {
  text-align: center;
  color: #909399;
  padding: 30px 0;
}
</style>
